﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SimpleDBLib
{
    /// <summary>
    /// Singleton class for managing file access - 
    /// Keep track of all file streams
    /// Idea: save time of open \ close stream
    /// </summary>
    /// 
    public sealed class FileManager
    {
        static readonly FileManager instance = new FileManager();

        private string fileDBSchema = "db.dat";
        private FileStream streamDBSchema;
        private List<FileStream> streams;

        /// <summary>
        /// Property for returnning the shared instance 
        /// </summary>
        public static FileManager sharedInstance
        {
            get
            {
                return instance;
            }
        }
        /// <summary>
        /// Static constructor for the singleton design pattern
        /// </summary>
        static FileManager()
        {            
        }        
        /// <summary>
        /// Default constructor
        /// </summary>
        FileManager()
        {
            if (File.Exists(fileDBSchema))
            {
                streamDBSchema = new FileStream(fileDBSchema, FileMode.Open, FileAccess.ReadWrite); //Open existing schema
            }
            else
            {
                //Create new schema - set number of tables to 0
                streamDBSchema = new FileStream(fileDBSchema, FileMode.Create, FileAccess.ReadWrite);
                using (BinaryWriter writer = new BinaryWriter(streamDBSchema))
                {
                    int numberOfTables = 0;     //Initialize the new schema with 0 tables
                    writer.Write(numberOfTables);
                }                
            }
            streams = new List<FileStream>();
        }

        /// <summary>
        /// Close all open streams
        /// Call this function before closing the application
        /// </summary>
        public void CloseStreams()
        {
            foreach (FileStream stream in streams)
            {
                stream.Close();
            }
            streamDBSchema.Close();
        }
      





    }
}
